package com.shanshan.wheel.rpc.common.remoting.transport.clent;

import com.shanshan.wheel.rpc.common.remoting.dto.RpcResponse;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 该类用于存放已发送但未收到回复的请求（未处理请求类）
 * @ClassName UnprocessedRequests
 * @Author 山山大魔王
 * @Date 2022/9/5 11:58
 * @Version 1.0
 */
@Component
public class UnprocessedRequests {

    private final Map<String, CompletableFuture<RpcResponse<Object>>> UNPROCESSED_REQUEST_FUTURES = new ConcurrentHashMap<>();

    /**
     * 存储为收到回复的请求
     * @param requestId
     * @param future
     */
    public void put(String requestId, CompletableFuture<RpcResponse<Object>> future){
        UNPROCESSED_REQUEST_FUTURES.put(requestId, future);
    }

    /**
     * 设置结果
     * @param rpcResponse
     */
    public void complete(RpcResponse<Object> rpcResponse){
        // 删除响应对应的请求
        CompletableFuture<RpcResponse<Object>> future = UNPROCESSED_REQUEST_FUTURES.remove(rpcResponse.getRequestId());
        if(null != future){
            // 设置结果
            future.complete(rpcResponse);
        }
    }

}
